package com.example.common.filter;

import com.example.common.redis.RedisCache;
import com.example.model.user.dtos.LoginUser;
import com.example.utils.common.AppJwtUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    RedisCache redisCache;
    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        String token = httpServletRequest.getHeader("token");
        if(!StringUtils.hasText(token)){
            filterChain.doFilter(httpServletRequest,httpServletResponse);
//            ResponseUtil.out(httpServletResponse, ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH));
            return;
        }

        Jws<Claims> jws = AppJwtUtil.getJws(token);
        String user_id;
        try {
            Claims claims = jws.getBody();
            user_id = claims.get("id").toString();
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException("token非法");
        }

//        System.out.println(claims.get("id"));
        String redis_key = "acl_login:"+user_id;

        LoginUser loginUser = redisCache.getCacheObject(redis_key);
        if(Objects.isNull(loginUser)){
            throw new RuntimeException("用户未登录");
        }
        //TODO 获取权限信息


        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(loginUser,null,loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
        filterChain.doFilter(httpServletRequest,httpServletResponse);
    }
}
